const express = require('express');
const router = express.Router();
const multer = require('multer');
const busboy = require('busboy');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './14/static/img'); // 一直报错.我也不知道为啥.....我就只写文件名让他自己上传,然后我把文件目录打印出来
    //md终于找到为啥了,这个路径为什么会从项目路径开始?好奇怪啊
  },
  filename: function (req, file, cb) {
    const ext = file.originalname.split('.')[1];
    // 用时间拼接随机时间数
    const tmpname = new Date().getTime() + parseInt(Math.random() * 9999);
    cb(null, `${tmpname}.${ext}`);
  },

});
function fileFilter (req, file, cb) {
 
  let {mimetype}=file
  let types = ['jpg', 'jpeg', 'png', 'gif', 'webp']; // 允许上传类型
  let temType = mimetype.split('/')[1];
  if (types.indexOf(temType) == -1) {
    return cb(new Error('参数错误'))
  } else{
    cb(null, true)
  }
  
}
// 上传服务器的是一个对象,把single写的字段也就是key值,取出来.
const upload = multer({ storage , fileFilter, limits: { fileSize: 1 }});

router.post('/upload', upload.single('image'), (req, res) => {
  let { size, mimetype, path } = req.file;
  let types = ['jpg', 'jpeg', 'png', 'gif', 'webp']; // 允许上传类型
  // const img = req.file.path;
  // console.log(img);
  /* 这块我要笑死了....哥哥这块代码你就算报错依旧会传进去...哥哥... */
  let temType = mimetype.split('/')[1];
  if (size > 500000) {
    return res.send({ code: 200, msg: '尺寸过大,进不去' });
  } else if (types.indexOf(temType) == -1) {
    return res.send({ code: 200, msg: '媒体类型错误' });
  } else {
    let url = `/public/img/${req.file.filename}`;
    res.send({ code: 200, msg: 'nice', url });
  }
  // key值,属性值是地址; 这个key值必须和前端的key值保持统一.
});

module.exports = router;
